Exception Handling

Java Technologies - Java.lang প্যাকেজ (Java.lang Package)
118
118

Exception Handling একটি গুরুত্বপূর্ণ প্রক্রিয়া Java প্রোগ্রামিংয়ে, যা প্রোগ্রামের চলাকালীন সময়ে উদ্ভূত ত্রুটি (error) বা অবাঞ্ছিত পরিস্থিতি সঠিকভাবে মোকাবিলা করতে সহায়তা করে। Java-তে, ত্রুটি মোকাবিলা করার জন্য একটি শক্তিশালী এবং নমনীয় exception handling মেকানিজম রয়েছে যা প্রোগ্রামটির স্থিতিশীলতা এবং নির্ভরযোগ্যতা বৃদ্ধি করে।

Exception Handling এর মৌলিক ধারণা:

Java-তে Exception Handling প্রধানত try-catch, throw, throws, এবং finally ব্লক ব্যবহার করে। এটি runtime ত্রুটির ক্ষেত্রে প্রোগ্রামটি ক্র্যাশ না হয়ে সঠিকভাবে কাজ করার সুযোগ দেয়।

Exception Types:

Java তে দুই ধরনের এক্সেপশন (Exception) রয়েছে:

  1. Checked Exception:
    • Checked Exception এমন এক্সেপশন যা compile-time এ ধরা পড়ে এবং এগুলোকে explicitly handle করতে হয় (যেমন IOException, SQLException)।
    • আপনি যদি একটি checked exception ফেলে দেন, তবে আপনাকে তা throws কিওয়ার্ড দিয়ে ঘোষণা করতে হবে অথবা try-catch ব্লকের মধ্যে হ্যান্ডেল করতে হবে।
  2. Unchecked Exception:
    • Unchecked Exception এমন এক্সেপশন যা runtime এর সময় ঘটে এবং এগুলো compile-time এ ধরা পড়ে না (যেমন NullPointerException, ArithmeticException)।
    • এগুলোকে handle করা অবশ্যই বাধ্যতামূলক নয়, তবে সেগুলোর জন্য proper exception handling রাখা উচিত।
  3. Error:
    • Errors হল serious issues, যেমন OutOfMemoryError, যা সাধারণত application-এ handle করা যায় না। এগুলি JVM দ্বারা জেনারেট করা হয় এবং সেগুলি থ্রেডের exception handling এর বাইরে থাকে।

Exception Handling Syntax

Java exception handling-এর জন্য try, catch, throw, throws, এবং finally ব্লক ব্যবহৃত হয়।

1. try-catch block

  • try ব্লকটি এমন কোড রাখে যা ত্রুটির সম্ভাবনা থাকে এবং catch ব্লকটি সেই ত্রুটির ধরন অনুযায়ী কিভাবে হ্যান্ডেল করতে হবে তা নির্ধারণ করে।

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle the exception
}

উদাহরণ:

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: / by zero

2. Multiple catch blocks

  • একাধিক ধরনের exception একই try ব্লকের মধ্যে ক্যাচ করতে হলে, আপনি একাধিক catch ব্লক ব্যবহার করতে পারেন।

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
}

উদাহরণ:

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            String str = null;
            System.out.println(str.length());  // This will throw NullPointerException
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (NullPointerException e1) {
            System.out.println("NullPointerException: " + e1.getMessage());
        } catch (ArithmeticException e2) {
            System.out.println("ArithmeticException: " + e2.getMessage());
        }
    }
}

Output:

NullPointerException: Cannot invoke "String.length()" because "str" is null

3. finally block

  • finally ব্লকটি এমন একটি ব্লক যা try এবং catch ব্লক এর পর অবশ্যই execute হয়, चाहे ত্রুটি ঘটুক বা না ঘটুক। এটি সাধারণত resources (যেমন database connection, file streams) বন্ধ করার জন্য ব্যবহৃত হয়।

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Cleanup code that will always run
}

উদাহরণ:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        } finally {
            System.out.println("This will always be executed");
        }
    }
}

Output:

Caught Exception: / by zero
This will always be executed

4. throw keyword

  • throw কিওয়ার্ড ব্যবহার করে আপনি একটি exception manually ফেলে দিতে পারেন। এটি সাধারণত custom exception তৈরি করতে ব্যবহৃত হয়।

Syntax:

throw new ExceptionType("Exception message");

উদাহরণ:

public class ThrowExample {
    public static void main(String[] args) {
        try {
            validateAge(15);  // This will throw IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }

    public static void validateAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age should be 18 or older");
        }
    }
}

Output:

Caught Exception: Age should be 18 or older

5. throws keyword

  • throws কিওয়ার্ড ব্যবহার করে আপনি একটি method-এ যে exception ফেলা হবে তা ঘোষণা করতে পারেন। এটি সাধারণত checked exceptions এর ক্ষেত্রে ব্যবহৃত হয়।

Syntax:

public void myMethod() throws ExceptionType {
    // Code that might throw an exception
}

উদাহরণ:

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            checkAge(15);  // This will throw an exception
        } catch (Exception e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }

    public static void checkAge(int age) throws IllegalArgumentException {
        if (age < 18) {
            throw new IllegalArgumentException("Age should be 18 or older");
        }
    }
}

Output:

Caught Exception: Age should be 18 or older

Java Exception Handling Best Practices:

  1. Catch Specific Exceptions First:
    • সর্বদা সবচেয়ে নির্দিষ্ট এক্সেপশন প্রথমে ক্যাচ করুন, এবং তারপর আরও সাধারণ এক্সেপশনগুলি (যেমন Exception) পরে ধরুন।
  2. Use Finally Block for Cleanup:
    • যেকোনো resources (যেমন ফাইল, ডাটাবেস কানেকশন) ক্লোজ করতে finally block ব্যবহার করুন।
  3. Avoid Empty Catch Blocks:
    • কখনোই খালি catch ব্লক ব্যবহার করবেন না। কমপক্ষে ত্রুটির মেসেজ লগ করুন বা তা ইউজারকে জানান।
  4. Don't Catch Throwable:
    • Throwable ক্যাচ করা এড়িয়ে চলুন, কারণ এটি Error এবং Exception উভয়ই কভার করে, যেগুলির মধ্যে অনেকটাই সফটওয়্যার বা সিস্টেম স্তরের ত্রুটি থাকতে পারে যেগুলি handle করা সম্ভব নয়।
  5. Log Exception Details:
    • ত্রুটি ধরার পর, ত্রুটির বিস্তারিত লগ করুন। এতে debugging এবং troubleshooting সহজ হয়।

Exception Handling একটি অত্যন্ত গুরুত্বপূর্ণ ধারণা Java প্রোগ্রামিংয়ে, যা কোডের স্থিতিশীলতা এবং নির্ভরযোগ্যতা বজায় রাখে। try-catch, throw, throws, এবং finally ব্লক ব্যবহার করে ত্রুটিগুলিকে সঠিকভাবে পরিচালনা করা যেতে পারে এবং প্রোগ্রামটি ক্র্যাশ না হয়ে সঠিকভাবে চলতে থাকে।

Content added By

Exception Handling এর ভূমিকা

112
112

Exception Handling Java-তে একটি অত্যন্ত গুরুত্বপূর্ণ বিষয়, যা প্রোগ্রামে ত্রুটি বা অপ্রত্যাশিত পরিস্থিতি (errors) সঠিকভাবে পরিচালনা করতে সাহায্য করে। এটি Java প্রোগ্রামের কার্যক্রমের মধ্যে কোনো সমস্যা ঘটলে, সেই সমস্যা সনাক্ত করতে, মোকাবিলা করতে এবং সংশোধন করতে সহায়তা করে। Exception Handling প্রোগ্রামটিকে স্থিতিশীল এবং নির্ভরযোগ্য করে তোলে, কারণ এটি runtime errors (যেমন, ইনপুট ভুল হওয়া, ফাইল খুঁজে না পাওয়া, ডিভাইসের সাথে যোগাযোগের সমস্যা) থেকে অ্যাপ্লিকেশনকে নিরাপদ রাখে।

Java তে exception handling একটি structured পদ্ধতিতে কাজ করে যা কোডের ক্র্যাশ বা ব্যর্থতা কমানোর জন্য প্রয়োজনীয় ব্যবস্থা গ্রহণ করতে সক্ষম হয়।

Exception Handling এর ভূমিকা:

  1. Error Detection and Recovery:
    • Exception handling কোডের মধ্যে ত্রুটি সনাক্ত করতে সাহায্য করে এবং এটি এক ধরনের recovery mechanism সরবরাহ করে, যাতে প্রোগ্রামটি ক্র্যাশ না হয়। যখন কোনো ত্রুটি ঘটে, তখন অ্যাপ্লিকেশন বন্ধ না হয়ে, কিছু ব্যবস্থা গ্রহণ করা যায়।
  2. Separation of Normal and Error Code:
    • Exception Handling কোডের মধ্যে সাধারণ কার্যকলাপ এবং ত্রুটি মোকাবেলার কোড আলাদা করে। এর ফলে ত্রুটি মোকাবেলার কোড (যেমন try-catch ব্লক) এবং সাধারণ কোড (যেমন ফাংশন বা মেথড) একে অপর থেকে পৃথক থাকে, যা কোডটিকে পরিষ্কার এবং পরিচালনা করা সহজ করে।
  3. Graceful Program Termination:
    • Graceful termination মানে হলো ত্রুটি ঘটলেও প্রোগ্রামটি এমনভাবে শেষ হওয়া যাতে সিস্টেম বা অ্যাপ্লিকেশন নষ্ট না হয়ে যায়। Exception handling এর মাধ্যমে, আপনি অ্যাপ্লিকেশনটি বন্ধ করার পূর্বে প্রয়োজনীয় রিসোর্স রিলিজ করতে পারেন (যেমন, ফাইল বন্ধ করা, মেমরি মুক্ত করা, ডাটাবেস সংযোগ বন্ধ করা ইত্যাদি)।
  4. Error Logging and Debugging:
    • Exception handling ত্রুটির সময় আপনাকে যথাযথ logging বা debugging তথ্য প্রদান করতে সহায়তা করে। এটি ত্রুটি ট্রেস (stack trace) প্রদান করে, যা ডেভেলপারকে সমস্যার উৎস খুঁজে বের করতে সাহায্য করে।
  5. User-Friendly Messages:
    • Exception handling ব্যবহারকারীকে স্পষ্ট এবং সহজ ভাষায় ত্রুটির ব্যাখ্যা প্রদান করতে সহায়তা করে, যার ফলে ব্যবহারকারী জানে কোন ত্রুটি ঘটেছে এবং কীভাবে তা ঠিক করা যাবে।

Exception Handling এর মেকানিজম

Java তে Exception Handling 4টি মূল ব্লক দ্বারা কাজ করে:

  1. try block:

    • যেখানে আপনি code লিখেন যেটি ত্রুটিপূর্ণ হতে পারে। যদি কোনো exception ঘটে, তবে এটি catch block এ চলে যাবে।

    উদাহরণ:

    try {
        int result = 10 / 0; // Division by zero will cause ArithmeticException
    }
    
  2. catch block:

    • এটি exception ধরতে ব্যবহৃত হয়। যখন একটি exception ঘটবে, তখন try block এর execution থামিয়ে catch block চলবে।

    উদাহরণ:

    catch (ArithmeticException e) {
        System.out.println("Error: Division by zero!");
    }
    
  3. finally block:

    • এটি অবশ্যম্ভাবীভাবে 실행 হয়, exception ঘটুক বা না ঘটুক। এটি সাধারণত রিসোর্স বন্ধ করার জন্য ব্যবহৃত হয় (যেমন ফাইল বা ডাটাবেস কনেকশন বন্ধ করা)।

    উদাহরণ:

    finally {
        System.out.println("This will always be executed.");
    }
    
  4. throw keyword:

    • আপনি নিজে exception তৈরি করতে throw কিওয়ার্ড ব্যবহার করতে পারেন। এটি সাধারণত কাস্টম exception তৈরি করার জন্য ব্যবহৃত হয়।

    উদাহরণ:

    throw new ArithmeticException("Custom error message");
    
  5. throws keyword:

    • মেথড সিগনেচারে throws কিওয়ার্ড ব্যবহার করে আপনি একটি মেথডের মধ্যে সম্ভাব্য exception গুলি ঘোষণা করতে পারেন, যা সেই মেথডে ঘটতে পারে। এটি exception এর প্রাসঙ্গিক হ্যান্ডলিং দায় অন্য মেথডের উপর চাপিয়ে দেয়।

    উদাহরণ:

    public void method() throws IOException {
        // some code that may throw IOException
    }
    

Exception Handling এর উদাহরণ:

import java.io.*;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("This will always be executed.");
        }

        try {
            FileReader file = new FileReader("nonexistentfile.txt");  // This will throw FileNotFoundException
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Output:

Error: / by zero
This will always be executed.
File not found: nonexistentfile.txt

Exception Handling এর সুবিধা:

  1. Improves Code Quality: Exception handling ensures that your application handles errors effectively and does not crash unexpectedly.
  2. Better Debugging: When an exception occurs, you can get the stack trace, which helps in debugging and locating the exact issue.
  3. User Experience: By handling exceptions, you can provide more meaningful error messages to users, improving their experience.
  4. Resource Management: You can release resources (like file handles or database connections) in the finally block, ensuring they are properly closed even if an exception occurs.

Exception Handling Java প্রোগ্রামের একটি অত্যন্ত গুরুত্বপূর্ণ অংশ যা ত্রুটিগুলি সঠিকভাবে মোকাবিলা করতে সহায়তা করে, ফলে প্রোগ্রামটির স্থিতিশীলতা এবং নির্ভরযোগ্যতা বৃদ্ধি পায়। সঠিকভাবে exception handling প্রোগ্রামটির আচরণকে আগের চেয়ে আরো বেশি নিয়ন্ত্রণযোগ্য এবং উপযোগী করে তোলে, এবং এটি ডেভেলপারকে কার্যকারিতা উন্নত করতে সহায়তা করে।

Content added By

Checked এবং Unchecked Exception এর ধারণা

119
119

Java তে Exceptions দুই ধরনের হয়: Checked Exceptions এবং Unchecked Exceptions। এই দুটি ধরণের এক্সসেপশন ব্যবস্থাপনা প্রক্রিয়া এবং কীভাবে এগুলি কোডে ব্যবহৃত হয় তার মধ্যে কিছু মৌলিক পার্থক্য রয়েছে।

1. Checked Exceptions:

Checked Exceptions হলো এমন ধরনের এক্সসেপশন, যেগুলি compile-time এ চেক করা হয় এবং এটি অবশ্যই handle (ধরা) করতে হবে বা declare (ঘোষণা) করতে হবে। যদি আপনি checked exception কে handle না করেন, তবে কম্পাইলার আপনাকে একটি compile-time error দিবে।

কীভাবে কাজ করে?

  • Checked exceptions সাধারণত এমন পরিস্থিতিতে ঘটে যেখানে কোনো অপারেশন ব্যর্থ হতে পারে, কিন্তু এটি সম্ভাব্যভাবে সমাধান করা যেতে পারে। যেমন, ফাইল পড়ার সময় বা নেটওয়ার্কের সাথে সংযোগ স্থাপন করার সময় ত্রুটি ঘটতে পারে, কিন্তু তা ঠিক করা সম্ভব।
  • যখন কোনো checked exception ঘটে, তখন এটি try-catch ব্লক দ্বারা ধরতে হয় বা throws কিওয়ার্ডের মাধ্যমে মেথড সিগনেচারে ডিক্লেয়ার করতে হয়।

Examples:

  • IOException
  • SQLException
  • ClassNotFoundException

উদাহরণ:

import java.io.*;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("somefile.txt");
            BufferedReader reader = new BufferedReader(file);
            String line = reader.readLine();
            System.out.println(line);
        } catch (IOException e) {
            System.out.println("An IOException occurred: " + e.getMessage());
        }
    }
}

Explanation:

  • এখানে IOException একটি checked exception, তাই এটি try-catch ব্লক দ্বারা handle করা হয়েছে।

2. Unchecked Exceptions:

Unchecked Exceptions হল এমন এক্সসেপশন যা runtime এ ঘটে এবং এটি compile-time এ চেক করা হয় না। এগুলি RuntimeException এর সাবক্লাস। Unchecked exception গুলি সাধারণত programming errors এর কারণে ঘটে, যেমন null pointer access বা array index out of bounds

কীভাবে কাজ করে?

  • Unchecked exceptions ত্রুটি সৃষ্টিকারী কোডে আগেই উল্লেখ করা প্রয়োজন নয়, অর্থাৎ এটি explicitly handle করতে হবে না।
  • যেহেতু এগুলি runtime এ ঘটতে পারে, তাই try-catch ব্লক ব্যবহার করা বাধ্যতামূলক নয়, তবে এটি ব্যবহার করা যেতে পারে।

Examples:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException

উদাহরণ:

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        
        try {
            // Accessing index beyond the array size
            System.out.println(numbers[10]); // This will throw ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
        }
    }
}

Explanation:

  • এখানে ArrayIndexOutOfBoundsException একটি unchecked exception, যা runtime এ ঘটেছে। আমরা এটি try-catch ব্লকের মাধ্যমে handle করেছি, তবে এটি handle না করলেও compilation এর সময় কোন ত্রুটি হতো না।

Difference between Checked and Unchecked Exceptions:

FeatureChecked ExceptionUnchecked Exception
DefinitionExceptions that must be explicitly handled at compile time.Exceptions that are not checked at compile time.
SubclassSubclass of Exception (but not subclass of RuntimeException).Subclass of RuntimeException.
ExamplesIOException, SQLException, ClassNotFoundException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Handling RequirementMust be handled with try-catch block or declared with throws.Optional handling (no compile-time check).
Compile-Time CheckYes, compile-time check is mandatory.No, compile-time check is not required.
When They OccurOccur due to external factors (e.g., I/O operations, database access).Occur due to bugs or logical errors in the program.
Performance OverheadMay add overhead due to mandatory handling.Generally does not cause significant performance overhead.

When to Use Checked and Unchecked Exceptions?

  • Use Checked Exceptions: When the error is recoverable and requires the caller to handle it explicitly. For example, errors in I/O operations, database connections, or network connections.
  • Use Unchecked Exceptions: When the error occurs due to a programming mistake or logical error that the programmer can prevent (e.g., NullPointerException, ArithmeticException). These should be used for bugs that should be fixed during development rather than handled in production.

Summary:

  • Checked Exceptions: Must be handled or declared, often occur due to external issues, and require the programmer to manage them explicitly.
  • Unchecked Exceptions: Do not need to be handled explicitly, often caused by programming errors, and typically indicate bugs in the code.
Content added By

Common Exception ক্লাসসমূহ: NullPointerException, IOException, ArithmeticException

136
136

Java-তে বিভিন্ন ধরনের Exception রয়েছে, যা প্রোগ্রাম চলাকালীন সময়ে বিভিন্ন সমস্যার কারণে ঘটতে পারে। এখানে তিনটি কমন exception ক্লাস নিয়ে আলোচনা করা হবে: NullPointerException, IOException, এবং ArithmeticException


1. NullPointerException

NullPointerException হলো একটি runtime exception যা তখন ঘটে যখন আপনি কোনো null ভ্যালু ধারণকারী অবজেক্ট বা রেফারেন্সের উপর কোনো মেথড কল বা প্রপার্টি অ্যাক্সেস করার চেষ্টা করেন। এটি খুবই সাধারণ একটি ত্রুটি এবং Java-তে ডেভেলপারদের কাছে অনেক পরিচিত।

কারণ:

  • যদি আপনি কোনো অবজেক্ট বা ভেরিয়েবলকে null সেট করেন এবং পরে সেই ভেরিয়েবলের সাথে কোনো অ্যাকশন (যেমন method call বা property access) করতে যান, তবে এটি একটি NullPointerException তৈরি করবে।

উদাহরণ:

public class NullPointerExample {
    public static void main(String[] args) {
        String str = null;
        
        // Trying to call method on null object
        try {
            int length = str.length(); // This will throw NullPointerException
        } catch (NullPointerException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

Output:

Caught Exception: null

Explanation:

  • str ভেরিয়েবলটি null দিয়ে ইনিশিয়ালাইজ করা হয়েছে। str.length() মেথড কল করার সময় NullPointerException ঘটে, কারণ str এর কোন অবজেক্ট নেই।

2. IOException

IOException হলো একটি checked exception যা সাধারণত ইন্টারঅ্যাকটিভ ফাইল সিস্টেম বা নেটওয়ার্কের মাধ্যমে I/O অপারেশন করার সময় ঘটে। এটি বিভিন্ন ধরণের সমস্যাকে চিহ্নিত করে, যেমন ফাইল না পাওয়া, ফাইল পড়তে বা লিখতে ব্যর্থতা, ইত্যাদি।

কারণ:

  • যখন আপনি ফাইল থেকে ডেটা পড়া বা লেখার চেষ্টা করেন এবং কোনো সমস্যা সৃষ্টি হয় (যেমন ফাইল না পাওয়া, অথবা অনুমতি সমস্যা), তখন একটি IOException সৃষ্টি হয়।

উদাহরণ:

import java.io.*;

public class IOExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("nonexistentfile.txt"); // This file doesn't exist
            BufferedReader reader = new BufferedReader(file);
            String line = reader.readLine();
            System.out.println(line);
        } catch (IOException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

Output:

Caught Exception: nonexistentfile.txt (No such file or directory)

Explanation:

  • কোডটিতে FileReader দিয়ে nonexistentfile.txt নামের ফাইলটি পড়ার চেষ্টা করা হচ্ছে। যেহেতু ফাইলটি উপস্থিত নেই, তাই IOException ঘটে এবং ফাইলের সাথে সম্পর্কিত একটি ত্রুটি বার্তা প্রদর্শিত হয়।

3. ArithmeticException

ArithmeticException হলো একটি runtime exception যা তখন ঘটে যখন আপনি গাণিতিকভাবে একটি অযাচিত বা অপ্রত্যাশিত অপারেশন করেন, যেমন শূন্য দ্বারা ভাগ করা (division by zero)।

কারণ:

  • যখন কোনো সংখ্যাকে 0 দ্বারা ভাগ করার চেষ্টা করা হয়, তখন এটি একটি ArithmeticException তৈরি করে।

উদাহরণ:

public class ArithmeticExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Division by zero will cause ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

Output:

Caught Exception: / by zero

Explanation:

  • এখানে 10 / 0 এক্সপ্রেশনটি একটি ArithmeticException তৈরি করবে, কারণ শূন্য দ্বারা ভাগ করা সম্ভব নয়। এটি একটি runtime exception, তাই try-catch ব্লক দিয়ে এর সাথে মোকাবিলা করা হয়েছে।

Summary of Common Exception Classes:

ExceptionDescriptionWhen it Occurs
NullPointerExceptionHappens when trying to access methods or fields of a null object reference.Accessing methods or fields of null objects.
IOExceptionOccurs during I/O operations (reading/writing to files, network, etc.).Reading or writing to files, network issues.
ArithmeticExceptionOccurs during invalid arithmetic operations, such as division by zero.Invalid arithmetic operation (e.g., 10 / 0).

Best Practices:

  • NullPointerException: Always check if an object is null before invoking methods or accessing fields. Use Optional where applicable for safe handling.
  • IOException: Always handle file I/O operations with proper exception handling and ensure that resources are closed in a finally block or using try-with-resources.
  • ArithmeticException: Validate inputs, especially when performing arithmetic operations like division. Always check for division by zero or other invalid arithmetic operations.

Java তে NullPointerException, IOException, এবং ArithmeticException এর মতো common exception গুলি প্রোগ্রাম চলাকালীন সময়ে সাধারণত ঘটে। এগুলি সঠিকভাবে হ্যান্ডেল করা প্রোগ্রামের স্থিতিশীলতা নিশ্চিত করতে সাহায্য করে এবং ব্যবহারকারীদের জন্য একটি ভাল ব্যবহারযোগ্য অভিজ্ঞতা প্রদান করে।

Content added By

Exception Handling এর জন্য মেথড: try, catch, throw, throws, finally

102
102

Exception Handling Java-তে ত্রুটির মোকাবিলার জন্য একটি গুরুত্বপূর্ণ প্রযুক্তি, যা প্রোগ্রামটি চলাকালীন সময়ে অপ্রত্যাশিত পরিস্থিতি থেকে সুরক্ষা দেয়। Java.lang প্যাকেজে পাওয়া যায় অনেক গুরুত্বপূর্ণ এক্সেপশন ক্লাস এবং মেথড যা exception handling এ ব্যবহৃত হয়।

Java-তে exception handling এর জন্য ৫টি গুরুত্বপূর্ণ কিওয়ার্ড রয়েছে:

  • try
  • catch
  • throw
  • throws
  • finally

এগুলো ব্যবহার করে Java-তে exception সঠিকভাবে handle করা যায়।


1. try - catch block

try এবং catch ব্লক ব্যবহার করে Java-তে exception handle করা হয়। যখন একটি exception ঘটে, তখন try ব্লকের কোড execute হতে থাকে, কিন্তু যখন কোনো exception ঘটে, তখন কোড execution থেমে গিয়ে catch ব্লক execute হয়।

try block:

  • try ব্লকে আপনি সেই কোড লিখবেন, যা ত্রুটিপূর্ণ হতে পারে। যদি exception ঘটে, তাহলে তা catch ব্লকে যাবে।

catch block:

  • catch ব্লকটি exception ধরা এবং তার সাথে কাজ করার জন্য ব্যবহৃত হয়।

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle the exception
}

Example:

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: / by zero

2. throw keyword

throw কিওয়ার্ড ব্যবহৃত হয় যখন আপনি নিজে exception manually ফেলতে চান। এটি সাধারণত কাস্টম exception তৈরি করার জন্য ব্যবহৃত হয়।

Syntax:

throw new ExceptionType("Exception message");

Example:

public class ThrowExample {
    public static void main(String[] args) {
        try {
            validateAge(15);  // This will throw IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }

    public static void validateAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age should be 18 or older");
        }
    }
}

Output:

Caught Exception: Age should be 18 or older

3. throws keyword

throws কিওয়ার্ড ব্যবহৃত হয় method সিগনেচারে, যাতে আপনি মেথডের মধ্যে যে exception সম্ভাব্যভাবে ঘটতে পারে তা ঘোষণা করতে পারেন। এটি checked exceptions এর জন্য ব্যবহৃত হয় এবং মেথডের caller (যে মেথড মেথডটি কল করে) এর উপর exception হ্যান্ডলিংয়ের দায়িত্ব চাপিয়ে দেয়।

Syntax:

public void myMethod() throws ExceptionType {
    // Code that might throw an exception
}

Example:

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            checkAge(15);  // This will throw an exception
        } catch (Exception e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }

    public static void checkAge(int age) throws IllegalArgumentException {
        if (age < 18) {
            throw new IllegalArgumentException("Age should be 18 or older");
        }
    }
}

Output:

Caught Exception: Age should be 18 or older

4. finally block

finally ব্লকটি এমন একটি ব্লক, যা always execute হয়, চাই exception ঘটুক বা না ঘটুক। এটি সাধারণত resources (যেমন ফাইল, ডাটাবেস সংযোগ) ক্লোজ করার জন্য ব্যবহৃত হয়। finally ব্লকটি exception handling এর শেষে always run হয়।

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Cleanup code that will always run
}

Example:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        } finally {
            System.out.println("This will always be executed.");
        }
    }
}

Output:

Caught Exception: / by zero
This will always be executed.

Exception Handling এর কাজের পদ্ধতি:

  1. Try:
    • যেখানেই exception ঘটতে পারে, সেখানেই try ব্লক ব্যবহার করুন।
  2. Catch:
    • catch ব্লক দিয়ে exception এর ধরন চিহ্নিত করে, তাকে handle করুন। একাধিক catch ব্লক ব্যবহার করা যেতে পারে।
  3. Throw:
    • throw ব্যবহার করে আপনি নিজে exception তৈরি করতে পারেন এবং তাকে আপনার কোডে throw করতে পারেন।
  4. Throws:
    • throws কিওয়ার্ড ব্যবহার করে আপনি মেথডে যে exception হতে পারে, তা declare করতে পারেন। এটি method caller কে exception হ্যান্ডলিংয়ের দায়িত্ব দেয়।
  5. Finally:
    • finally ব্লক এমন কোড থাকবে যা চাই exception ঘটুক বা না ঘটুক, শেষপর্যন্ত execute হবে। এটি সাধারণত resources clean-up করার জন্য ব্যবহৃত হয়।

  • Exception handling Java প্রোগ্রামে ত্রুটি বা ভুল ব্যবস্থাপনা করার একটি অত্যন্ত গুরুত্বপূর্ণ বিষয়।
  • try-catch, throw, throws, এবং finally কিওয়ার্ড ব্যবহার করে আপনি exceptions যথাযথভাবে handle করতে পারেন।
  • এটি runtime errors থেকে প্রোগ্রামকে সুরক্ষা প্রদান করে এবং user-friendly error messages প্রদান করে, যাতে প্রোগ্রামটি ক্র্যাশ না হয়।
Content added By
Promotion